<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Layui</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../../layui/css/layui.css" media="all">
  <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
  <script src="../../js/common.js"></script>
  <style>
    .search-style {
      margin-left: 5%;
    }
  </style>
</head>

<body>
  <table class="layui-hide" id="test" lay-filter="test" lay-data="{id: 'idTest'}"></table>

  <!-- 工具栏模板： -->
  <script type="text/html" id="toolbarDemo">
      <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="delete">批量删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="update">编辑</button>
        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
      </div>

      <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">修改</a>
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="delete" style="background-color:#FF5511;">
          <font color="FFFFFF">删除</font>
        </a>
    </script>



  <!-- 显示序号 -->
  <script type="text/html" id="titleTpl">
    {{d.LAY_TABLE_INDEX+1}}
  </script>


  <!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
  <script src="../../layui/layui.js" charset="utf-8"></script>
  <script type="text/javascript">

    layui.use('table', function () {
      //得到各种内置组件
      var layer = layui.layer //弹层
        ,
        laypage = layui.laypage //分页
        ,
        laydate = layui.laydate //日期
        ,
        table = layui.table //表格
        ,
        carousel = layui.carousel //轮播
        ,
        upload = layui.upload //上传
        ,
        element = layui.element //元素操作
        ,
        slider = layui.slider //滑块
        ,
        dropdown = layui.dropdown //下拉菜单
        ,
        $ = layui.$

      var table = layui.table;
      let curr;
      let limit;
      var tableIns = table.render({
        elem: '#test',
        id: 'testReload',
        url: "/api/READ/api/my/sensitive/list",
        headers: {
          token: localStorage.token
        },
        cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增,
        height: 'full-80',//高度最大化减去差值 ,
        toolbar: '#toolbarDemo',
        page: true, //开启分页
        limit: 10,
        limits: [10, 15, 40, 60],
        request: {
          //这里设置的pageNum与pageSize每次请求时都会传给后端，从而实现layui的自定义分页
          pageName: 'current', //页码的参数名称，默认：page
          limitName: 'pageSize', //每页数据量的参数名，默认：limit
        },
        parseData: function (res) { //res 即为原始返回的数据
          //console.log(res);
          return {
            "code": res.code, //解析接口状态
            "msg": res.msg, //解析提示文本
            "data": res.data, //解析数据列表
            "count": res.total //总共条数
          };

        },
        response: {
          statusCode: 200 //规定成功的状态码，默认：0
        },

        cols: [
          [{
            type: 'checkbox',
            fixed: 'left'
          },
          {
            field: 'id',
            title: '序号',
            width: '10%',
            fixed: 'left',
            align: 'center',
            templet: '#titleTpl'
          },
          {
            field: 'id',
            width: '10%',
            title: 'ID',
            align: 'center',
            hide: true
          }, {
            field: 'sensitive',
            width: '20%',
            align: 'center',
            title: '敏感词'
          }, {
            field: 'createTime',
            width: '18%',
            align: 'center',
            title: '创建时间'
          }, {
            fixed: 'right',
            width: '15%',
            align: 'center',
            toolbar: '#barDemo'
          }

          ]
        ],
        done: function (res) {
          //如果是异步请求数据方式，res即为你接口返回的信息。
          //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
          // console.log(res);
        }
      });

      //监听头工具栏事件
      table.on('toolbar(test)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        data = checkStatus.data; //获取选中的数据
        // console.log(data[0].uid)

        switch (obj.event) {
          case 'update':
            if (data.length === 0) {
              layer.msg('请选择一行');
            } else if (data.length > 1) {
              layer.msg('只能同时编辑一个');
            } else {
              layer.alert('编辑 [uid]：' + checkStatus.data[0].uid);
            }
            break;

          case 'add':
            layer.open({
              type: 2, //打开一个iframe
              title: '添加敏感词',
              content: './add_sensitive.html',
              maxmin: true,
              area: ['350px', '300px'],
              btn: ['确定', '取消'],
              yes: function (res) {
                window.location.reload();
              }
            });
            break;

          case 'delete':
            var dataList = checkStatus.data;
            var len = dataList.length;
            var ids = new Array(len);

            for (var i = 0; i < len; ++i) {
              ids[i] = dataList[i].uid;
            }
            // console.log(ids);

            layer.msg('是否刪除 ' + len + ' 条用户数据', {
              time: 5000, //5s后自动关闭
              btn: ['确定', '取消'],
              yes: function (index) {
                //TODO 此时进行ajax的服务器访问，如果返回数据正常，则进行后面代码的调用
                $.ajax({
                  type: 'delete',
                  url: '/api/READ/api/my/user/deletes',
                  async: false,
                  dataType: "json",
                  headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                    token: localStorage.token
                  }, //接口json格式
                  data: JSON.stringify(ids),
                  success: function (res) {
                    layer.msg(res.msg);
                    layer.close(index);
                    window.location.reload();
                  }
                })
                layer.close(index);
              }
            });
            break;
        };
      });

      //监听行工具事件
      table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data, //获得当前行数据
          layEvent = obj.event,
          id = data.id //获得 lay-event 对应的值

        if (layEvent === 'detail') {
          layer.open({
            type: 2, //打开一个iframe
            title: '修改敏感词',
            content: './update_sensitive.html?id=' + id,
            maxmin: true,
            area: ['350px', '300px'],
            btn: ['确定', '取消'],
            yes: function (res) {
              window.location.reload();
            }
          });

        } else {
          var k = 0;
          if (localStorage.type >= 90 && localStorage.type <= 99) {
            k = 1;
          }
          if (localStorage.type == 21) {
            k = 1;
          }
          if (k == 0) {
            layer.msg('没有删除权限');
            return;
          }

          layer.msg('是否刪除', {
            time: 5000, //5s后自动关闭
            btn: ['确定', '取消'],
            yes: function (index) {
              $.ajax({
                type: 'delete',
                url: '/api/READ/api/my/sensitive/delete/'+id,
                async: false,
                dataType: "json",
                headers: {
                  'Content-Type': 'application/json;charset=utf-8',
                  token: localStorage.token
                }, 
                success: function (res) {
                  if (res.code == '200') {
                    layer.msg("删除成功");
                    setTimeout(() => {
                      window.location.reload();
                    },1000)

                  } else {
                    layer.alert("删除失败",{
                      title: "提示"
                    })

                  }
                }
              })
              layer.close(index);
            }
          });
        }
      });
    });
  </script>

</body>

</html>